package com.pearadmin.system.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.*;
import com.deepoove.poi.data.style.TableStyle;
import com.deepoove.poi.policy.HackLoopTableRenderPolicy;
import com.deepoove.poi.policy.LoopColumnTableRenderPolicy;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pearadmin.common.config.proprety.TemplateProperty;
import com.pearadmin.common.tools.common.FileUtil;
import com.pearadmin.common.tools.secure.SecurityUtil;
import com.pearadmin.common.tools.sequence.SequenceUtil;
import com.pearadmin.common.web.domain.request.PageDomain;
import com.pearadmin.system.domain.*;
import com.pearadmin.system.domain.model.ReportBaseinfoModel;
import com.pearadmin.system.mapper.*;
import com.pearadmin.system.service.*;
import com.pearadmin.system.util.FileToMultipartFileUtil;
import com.pearadmin.system.util.WordUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.TableRowAlign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 报告基本信息Service业务层处理
 *
 * @author ZSX
 * @date 2021-04-09
 */
@Service
public class ReportBaseinfoServiceImpl implements IReportBaseinfoService
{
    @Autowired
    private ReportBaseinfoMapper reportBaseinfoMapper;

    @Autowired
    private IReportCourseTargetService reportCourseTargetService;

    @Autowired
    private IReportTargetObservationContactService reportTargetObservationContactService;

    @Autowired
    private IReportEvaluateAbilityRelevanceService reportEvaluateAbilityRelevanceService;

    @Autowired
    private IReportAssessmentRationalityService reportAssessmentRationalityService;

    @Autowired
    private IReportUsualScoreStandardService reportUsualScoreStandardService;

    @Autowired
    private IReportEvaluationResultsService reportEvaluationResultsService;

    @Autowired
    private ITeacherAnalysisImprovementService teacherAnalysisImprovementService;

    @Autowired
    private ReportCourseTargetMapper reportCourseTargetMapper;

    @Autowired
    private ReportTargetObservationContactMapper reportTargetObservationContactMapper;

    @Autowired
    private ReportEvaluateAbilityRelevanceMapper reportEvaluateAbilityRelevanceMapper;

    @Autowired
    private ReportAssessmentRationalityMapper reportAssessmentRationalityMapper;

    @Autowired
    private ReportUsualScoreStandardMapper reportUsualScoreStandardMapper;

    @Autowired
    private ReportEvaluationResultsMapper reportEvaluationResultsMapper;

    @Autowired
    private TeacherAnalysisImprovementMapper teacherAnalysisImprovementMapper;

    @Resource
    private ISysFileService fileService;

    /**
     * 引 入 服 务
     */
    @Resource
    private SysFileMapper fileMapper;

    /**
     * 上 传 可 读 配 置
     */
    @Resource
    private TemplateProperty uploadProperty;



    /**
     * 查询报告基本信息
     *
     * @param id 报告基本信息ID
     * @return 报告基本信息
     */
    @Override
    public ReportBaseinfo selectReportBaseinfoById(Integer id)
    {
        return reportBaseinfoMapper.selectReportBaseinfoById(id);
    }

    /**
     * 查询报告基本信息列表
     *
     * @param reportBaseinfo 报告基本信息
     * @return 报告基本信息
     */
    @Override
    public List<ReportBaseinfo> selectReportBaseinfoList(ReportBaseinfo reportBaseinfo)
    {
        return reportBaseinfoMapper.selectReportBaseinfoList(reportBaseinfo);
    }

    /**
     * 查询报告基本信息
     * @param reportBaseinfo 报告基本信息
     * @param pageDomain
     * @return 报告基本信息 分页集合
     * */
    @Override
    public PageInfo<ReportBaseinfo> selectReportBaseinfoPage(ReportBaseinfo reportBaseinfo, PageDomain pageDomain)
    {
        SysUser sysUser = (SysUser) SecurityUtil.currentUserObj();
        PageHelper.startPage(pageDomain.getPage(),pageDomain.getLimit());
        List<ReportBaseinfo> data = reportBaseinfoMapper.selectReportBaseinfoList(reportBaseinfo);
        if(data !=null && !data.isEmpty()){
            for (ReportBaseinfo datum : data) {
                datum.setFileDesc(datum.getTitle() + ".docx");
                if(datum.getCreateBy().equalsIgnoreCase(sysUser.getUserId())){
                    datum.setSelf(true);
                }
            }
        }
        return new PageInfo<>(data);
    }

    /**
     * 新增报告基本信息
     *
     * @param reportBaseinfo 报告基本信息
     * @return 结果
     */

    @Override
    public int insertReportBaseinfo(ReportBaseinfo reportBaseinfo)
    {
        return reportBaseinfoMapper.insertReportBaseinfo(reportBaseinfo);
    }

    /**
     * 修改报告基本信息
     *
     * @param reportBaseinfo 报告基本信息
     * @return 结果
     */
    @Override
    public int updateReportBaseinfo(ReportBaseinfo reportBaseinfo)
    {
        return reportBaseinfoMapper.updateReportBaseinfo(reportBaseinfo);
    }

    /**
     * 删除报告基本信息对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteReportBaseinfoByIds(String[] ids)
    {
        return reportBaseinfoMapper.deleteReportBaseinfoByIds(ids);
    }

    /**
     * 删除报告基本信息信息
     *
     * @param id 报告基本信息ID
     * @return 结果
     */
    @Override
    public int deleteReportBaseinfoById(Integer id)
    {
        return reportBaseinfoMapper.deleteReportBaseinfoById(id);
    }

    /**
     * 保存报告及其关联信息
     * @param reportBaseinfoModel
     * @return
     */
    @Override
    @Transactional(readOnly = false)
    public boolean save(ReportBaseinfoModel reportBaseinfoModel) {
        SysUser sysUser = (SysUser) SecurityUtil.currentUserObj();
        // 存储基本信息
        ReportBaseinfo reportBaseinfo = reportBaseinfoModel.getReportBaseinfo();
        reportBaseinfo.setCreateTime(LocalDateTime.now());
        reportBaseinfo.setCreateBy(sysUser.getUserId());
        reportBaseinfo.setCreateName(sysUser.getUsername());
        insertReportBaseinfo(reportBaseinfo);

        // 存储课程目标
        List<ReportCourseTarget> reportCourseTargetList = reportBaseinfoModel.getReportCourseTargetList();
        if(reportCourseTargetList!=null && !reportCourseTargetList.isEmpty()){
            for (ReportCourseTarget reportCourseTarget : reportCourseTargetList) {
                reportCourseTarget.setCreateTime(LocalDateTime.now());
                reportCourseTarget.setCreateBy(sysUser.getUserId());
                reportCourseTarget.setCreateName(sysUser.getUsername());
                reportCourseTarget.setReportId(reportBaseinfo.getId().longValue());
                reportCourseTargetService.insertReportCourseTarget(reportCourseTarget);
            }
        }

        // 存储课程目标与毕业要求观测点的对应关系
        List<ReportTargetObservationContact> reportTargetObservationContactList = reportBaseinfoModel.getReportTargetObservationContactList();
        if(reportTargetObservationContactList!=null && !reportTargetObservationContactList.isEmpty()){
            for (ReportTargetObservationContact reportTargetObservationContact : reportTargetObservationContactList) {
                reportTargetObservationContact.setCreateTime(LocalDateTime.now());
                reportTargetObservationContact.setCreateBy(sysUser.getUserId());
                reportTargetObservationContact.setCreateName(sysUser.getUsername());
                reportTargetObservationContact.setReportId(reportBaseinfo.getId().longValue());
                reportTargetObservationContactService.insertReportTargetObservationContact(reportTargetObservationContact);
            }
        }

        // 存储评价内容与学生能力相关性
        List<ReportEvaluateAbilityRelevance> reportEvaluateAbilityRelevanceList = reportBaseinfoModel.getReportEvaluateAbilityRelevanceList();
        if(reportEvaluateAbilityRelevanceList!=null && !reportEvaluateAbilityRelevanceList.isEmpty()){
            for (ReportEvaluateAbilityRelevance reportEvaluateAbilityRelevance : reportEvaluateAbilityRelevanceList) {
                reportEvaluateAbilityRelevance.setCreateTime(LocalDateTime.now());
                reportEvaluateAbilityRelevance.setCreateBy(sysUser.getUserId());
                reportEvaluateAbilityRelevance.setCreateName(sysUser.getUsername());
                reportEvaluateAbilityRelevance.setReportId(reportBaseinfo.getId().longValue());
                reportEvaluateAbilityRelevanceService.insertReportEvaluateAbilityRelevance(reportEvaluateAbilityRelevance);
            }
        }

        // 存储考核合理性审核
        ReportAssessmentRationality reportAssessmentRationality = reportBaseinfoModel.getReportAssessmentRationality();
        reportAssessmentRationality.setCreateTime(LocalDateTime.now());
        reportAssessmentRationality.setCreateBy(sysUser.getUserId());
        reportAssessmentRationality.setCreateName(sysUser.getUsername());
        reportAssessmentRationality.setReportId(reportBaseinfo.getId().longValue());
        reportAssessmentRationalityService.insertReportAssessmentRationality(reportAssessmentRationality);

        // 存储平时成绩评分标准
        List<ReportUsualScoreStandard> reportUsualScoreStandardList = reportBaseinfoModel.getReportUsualScoreStandardList();
        if(reportUsualScoreStandardList!=null && !reportUsualScoreStandardList.isEmpty()){
            for (ReportUsualScoreStandard reportUsualScoreStandard : reportUsualScoreStandardList) {
                reportUsualScoreStandard.setCreateTime(LocalDateTime.now());
                reportUsualScoreStandard.setCreateBy(sysUser.getUserId());
                reportUsualScoreStandard.setCreateName(sysUser.getUsername());
                reportUsualScoreStandard.setReportId(reportBaseinfo.getId().longValue());
                reportUsualScoreStandardService.insertReportUsualScoreStandard(reportUsualScoreStandard);
            }
        }

        // 存储评价结果
        List<ReportEvaluationResults> reportEvaluationResultsList = reportBaseinfoModel.getReportEvaluationResultsList();
        if(reportEvaluationResultsList!=null && !reportEvaluationResultsList.isEmpty()){
            for (ReportEvaluationResults reportEvaluationResults : reportEvaluationResultsList) {
                reportEvaluationResults.setCreateTime(LocalDateTime.now());
                reportEvaluationResults.setCreateBy(sysUser.getUserId());
                reportEvaluationResults.setCreateName(sysUser.getUsername());
                reportEvaluationResults.setReportId(reportBaseinfo.getId().longValue());
                reportEvaluationResultsService.insertReportEvaluationResults(reportEvaluationResults);
            }
        }

        // 存储任课教师分析与改进
        TeacherAnalysisImprovement teacherAnalysisImprovement = reportBaseinfoModel.getTeacherAnalysisImprovement();
        teacherAnalysisImprovement.setCreateTime(LocalDateTime.now());
        teacherAnalysisImprovement.setCreateBy(sysUser.getUserId());
        teacherAnalysisImprovement.setCreateName(sysUser.getUsername());
        teacherAnalysisImprovement.setReportId(reportBaseinfo.getId().longValue());
        teacherAnalysisImprovementService.insertTeacherAnalysisImprovement(teacherAnalysisImprovement);

        reportBaseinfo.setWordId(saveWord(reportBaseinfoModel));
        updateReportBaseinfo(reportBaseinfo);
        return true;
    }

    /**
     * 保存word文档
     */
    private String saveWord(ReportBaseinfoModel reportBaseinfoModel) {
        ReportBaseinfo reportBaseinfo = reportBaseinfoModel.getReportBaseinfo();
        String templatePath = "F:\\IdeaProjects\\Pear-Admin-Boot\\pear-entrance\\src\\main\\resources\\templates\\模板文件.docx";
        String fileDir = "D:\\home";
        String fileShowName = reportBaseinfo.getTitle();
        Map<String, Object> paramsMap = new HashMap<>();
        // 渲染文本
        paramsMap.put("mainTitle", reportBaseinfo.getTitle());
        paramsMap.put("academic", reportBaseinfo.getAcademic());
        paramsMap.put("typeAndScore", reportBaseinfo.getTypeAndScore());
        paramsMap.put("classStudentNum", reportBaseinfo.getClassStudentNum());
        paramsMap.put("teacher", reportBaseinfo.getTeacher());
        paramsMap.put("assessmentMethod", reportBaseinfo.getAssessmentMethod());
        paramsMap.put("evaluationBasis", reportBaseinfo.getEvaluationBasis());

        List<ReportCourseTarget> reportCourseTargetList = reportBaseinfoModel.getReportCourseTargetList();
        List<Map<String, Object>> reportCourseTargetMapList = new ArrayList<Map<String, Object>>();
        if(reportCourseTargetList!=null && !reportCourseTargetList.isEmpty()){
            for (ReportCourseTarget reportCourseTarget : reportCourseTargetList) {
                Map<String,Object> map = new HashMap<>();
                map.put("title",reportCourseTarget.getTitle());
                map.put("content",reportCourseTarget.getContent());
                reportCourseTargetMapList.add(map);
            }
        }
        // 渲染课程目标
        paramsMap.put("reportCourseTargetMapList",reportCourseTargetMapList);

        // 渲染课程目标与毕业要求观测点的对应关系
        List<ReportTargetObservationContact> reportTargetObservationContactList = reportBaseinfoModel.getReportTargetObservationContactList();
        paramsMap.put("reportTargetObservationContactList",reportTargetObservationContactList);

        // 渲染评价内容与学生能力相关性
        List<ReportEvaluateAbilityRelevance> reportEvaluateAbilityRelevanceList = reportBaseinfoModel.getReportEvaluateAbilityRelevanceList();
        List<Integer> reportEvaluateAbilityRelevanceRowNumber = new ArrayList<>();
        reportEvaluateAbilityRelevanceRowNumber.add(0);
        TableRenderData reportEvaluateAbilityRelevanceTableRenderData = Tables.ofA4MediumWidth().center().create();
        List<RowRenderData> reportEvaluateAbilityRelevanceRowRenderDataList = new ArrayList<>();
        if(reportEvaluateAbilityRelevanceList!=null && !reportEvaluateAbilityRelevanceList.isEmpty()){
            RowRenderData reportEvaluateAbilityRelevanceHeader = Rows.of("课程目标","评价环节","评价内容","与学生能力相关性")
                    .bgColor("BDD6EE").center().textColor("000000").textFontFamily("宋体").textFontSize(12).textBold().create();
            reportEvaluateAbilityRelevanceRowRenderDataList.add(reportEvaluateAbilityRelevanceHeader);
            String firstName = reportEvaluateAbilityRelevanceList.get(0).getCourseObjectives();
            for (int i = 0;i < reportEvaluateAbilityRelevanceList.size(); i++) {
                ReportEvaluateAbilityRelevance reportEvaluateAbilityRelevance = reportEvaluateAbilityRelevanceList.get(i);
                if(!firstName.equals(reportEvaluateAbilityRelevance.getCourseObjectives())){
                    reportEvaluateAbilityRelevanceRowNumber.add(i);
                    firstName = reportEvaluateAbilityRelevance.getCourseObjectives();
                }
                RowRenderData row = Rows.of(reportEvaluateAbilityRelevance.getCourseObjectives(),reportEvaluateAbilityRelevance.getEvaluationLink()
                        ,reportEvaluateAbilityRelevance.getEvaluationContent(),reportEvaluateAbilityRelevance.getCapabilityRelevance()).textFontSize(10).center().create();
                reportEvaluateAbilityRelevanceRowRenderDataList.add(row);
            }
            if(reportEvaluateAbilityRelevanceRowNumber!=null && !reportEvaluateAbilityRelevanceRowNumber.isEmpty()){
                if(reportEvaluateAbilityRelevanceRowNumber.get(reportEvaluateAbilityRelevanceRowNumber.size()-1) != reportEvaluateAbilityRelevanceList.size()){
                    reportEvaluateAbilityRelevanceRowNumber.add(reportEvaluateAbilityRelevanceList.size());
                }
            }
            for (RowRenderData rowRenderData : reportEvaluateAbilityRelevanceRowRenderDataList) {
                reportEvaluateAbilityRelevanceTableRenderData.addRow(rowRenderData);
            }
            MergeCellRule.MergeCellRuleBuilder  reportEvaluateAbilityRelevanceMergeCellRuleBuilder = MergeCellRule.builder();

            for (int i = 0; i < reportEvaluateAbilityRelevanceRowNumber.size() - 1; i++) {
                reportEvaluateAbilityRelevanceMergeCellRuleBuilder.map(MergeCellRule.Grid.of(reportEvaluateAbilityRelevanceRowNumber.get(i)+1,0),MergeCellRule.Grid.of(reportEvaluateAbilityRelevanceRowNumber.get(i+1),0));
            }
            reportEvaluateAbilityRelevanceTableRenderData.setMergeRule(reportEvaluateAbilityRelevanceMergeCellRuleBuilder.build());

        }

        paramsMap.put("reportEvaluateAbilityRelevanceTableRenderData",reportEvaluateAbilityRelevanceTableRenderData);

        // 渲染考核合理性审核
        ReportAssessmentRationality reportAssessmentRationality = reportBaseinfoModel.getReportAssessmentRationality();
        paramsMap.put("semester",reportAssessmentRationality.getSemester());
        paramsMap.put("course",reportAssessmentRationality.getCourse());
        paramsMap.put("teacherpaper",reportAssessmentRationality.getTeacherpaper());
        paramsMap.put("teachercheck",reportAssessmentRationality.getTeachercheck());
        paramsMap.put("grade",reportAssessmentRationality.getGrade());

        // 解析毕业要求、毕业要求指标点、课程目标
        List<Map<String,Object>> gradeMapList = new ArrayList<>();
        if(StringUtils.isNotEmpty(reportAssessmentRationality.getGraduationRequirementsJson())){
            JSONArray graduationRequirementsJsonArray = JSON.parseArray(reportAssessmentRationality.getGraduationRequirementsJson());
            for (Object o : graduationRequirementsJsonArray) {
                JSONObject jsonObject = (JSONObject) o;
                Map<String,Object> map = new HashMap<>();
                map.put("graduationRequirements",jsonObject.getString("graduationRequirements"));
                map.put("indexPoint",jsonObject.getString("indexPoint"));
                map.put("courseObjectives",jsonObject.getString("courseObjectives"));
                gradeMapList.add(map);
            }
        }
        paramsMap.put("gradeMapList",gradeMapList);

        // 解析课程目标、试卷对应试题、分值
        List<Map<String,Object>> scoreMapList = new ArrayList<>();
        if(StringUtils.isNotEmpty(reportAssessmentRationality.getScoreJson())){
            JSONArray graduationRequirementsJsonArray = JSON.parseArray(reportAssessmentRationality.getScoreJson());
            for (Object o : graduationRequirementsJsonArray) {
                JSONObject jsonObject = (JSONObject) o;
                Map<String,Object> map = new HashMap<>();
                map.put("courseObjectives",jsonObject.getString("courseObjectives"));
                map.put("testQuestions",jsonObject.getString("testQuestions"));
                map.put("score",jsonObject.getString("score"));
                scoreMapList.add(map);
            }
        }
        paramsMap.put("scoreMapList",scoreMapList);

        // 解析试卷内容支撑
        List<Map<String,Object>> scoreContentMapList = new ArrayList<>();
        if(StringUtils.isNotEmpty(reportAssessmentRationality.getScoreContentJson())){
            JSONArray graduationRequirementsJsonArray = JSON.parseArray(reportAssessmentRationality.getScoreContentJson());
            for (Object o : graduationRequirementsJsonArray) {
                JSONObject jsonObject = (JSONObject) o;
                Map<String,Object> map = new HashMap<>();
                map.put("title",jsonObject.getString("title"));
                map.put("content",jsonObject.getString("content"));
                scoreContentMapList.add(map);
            }
        }
        paramsMap.put("scoreContentMapList",scoreContentMapList);
        paramsMap.put("courseGroupAuditOpinion",reportAssessmentRationality.getCourseGroupAuditOpinion());
        paramsMap.put("majorAuditOpinion",reportAssessmentRationality.getMajorAuditOpinion());

        // 解析平时成绩评分标准
        List<ReportUsualScoreStandard> reportUsualScoreStandardList = reportBaseinfoModel.getReportUsualScoreStandardList();
        paramsMap.put("reportUsualScoreStandardList",reportUsualScoreStandardList);

        // 解析评价结果
        List<ReportEvaluationResults> reportEvaluationResultsList = reportBaseinfoModel.getReportEvaluationResultsList();
        List<Integer> reportEvaluationResultsRowNumber = new ArrayList<>();
        reportEvaluationResultsRowNumber.add(0);
        TableRenderData  reportEvaluationResultsTableRenderData = Tables.ofA4MediumWidth().center().create();
        List<RowRenderData>  reportEvaluationResultsRowRenderDataList = new ArrayList<>();
        if(reportEvaluationResultsList!=null && !reportEvaluationResultsList.isEmpty()){
            RowRenderData header = Rows.of("课程目标","知识/能力","考核点","考核内容","考核权重","考核达成度","课程目标达成度")
                    .bgColor("BDD6EE").center().textColor("000000").textFontFamily("宋体").textFontSize(12).textBold().create();
            reportEvaluationResultsRowRenderDataList.add(header);
            String firstName = reportEvaluationResultsList.get(0).getCourseObjectives();
            for (int i = 0;i < reportEvaluationResultsList.size(); i++) {
                ReportEvaluationResults results = reportEvaluationResultsList.get(i);
                if(!firstName.equals(results.getCourseObjectives())){
                    reportEvaluationResultsRowNumber.add(i);
                    firstName = results.getCourseObjectives();
                }
                RowRenderData row = Rows.of(results.getCourseObjectives(),results.getKnowledgeAndAbility()
                        ,results.getAssessmentPoints(),results.getAssessmentContent(),results.getAssessmentPointsWeight().toString(),results.getAssessmentDegree(),results.getAchievementDegree().toString()).textFontSize(10).center().create();
                reportEvaluationResultsRowRenderDataList.add(row);
            }
            if(reportEvaluationResultsRowNumber!=null && !reportEvaluationResultsRowNumber.isEmpty()){
                if(reportEvaluationResultsRowNumber.get(reportEvaluationResultsRowNumber.size()-1) != reportEvaluationResultsList.size()){
                    reportEvaluationResultsRowNumber.add(reportEvaluationResultsList.size());
                }
            }
            for (RowRenderData rowRenderData : reportEvaluationResultsRowRenderDataList) {
                reportEvaluationResultsTableRenderData.addRow(rowRenderData);
            }
            MergeCellRule.MergeCellRuleBuilder  builder = MergeCellRule.builder();

            for (int i = 0; i < reportEvaluateAbilityRelevanceRowNumber.size() - 1; i++) {
                builder.map(MergeCellRule.Grid.of(reportEvaluateAbilityRelevanceRowNumber.get(i)+1,0),MergeCellRule.Grid.of(reportEvaluateAbilityRelevanceRowNumber.get(i+1),0));
                builder.map(MergeCellRule.Grid.of(reportEvaluateAbilityRelevanceRowNumber.get(i)+1,1),MergeCellRule.Grid.of(reportEvaluateAbilityRelevanceRowNumber.get(i+1),1));
                builder.map(MergeCellRule.Grid.of(reportEvaluateAbilityRelevanceRowNumber.get(i)+1,6),MergeCellRule.Grid.of(reportEvaluateAbilityRelevanceRowNumber.get(i+1),6));
            }
            reportEvaluationResultsTableRenderData.setMergeRule(builder.build());

        }

        paramsMap.put("reportEvaluationResultsTableRenderData",reportEvaluationResultsTableRenderData);

        // 解析任课教师分析与改进
        List<Map<String,Object>> teacherImgMapList = new ArrayList<>();
        TeacherAnalysisImprovement teacherAnalysisImprovement = reportBaseinfoModel.getTeacherAnalysisImprovement();
        List<String> imgList = Arrays.asList(teacherAnalysisImprovement.getImgUrl().split(";"));
        if(imgList.size() > 0){
            for (String s : imgList) {
                SysFile sysFile = fileMapper.selectByName(s);
                Map<String,Object> map = new HashMap<>();
                if("jpg".equalsIgnoreCase(sysFile.getFileType()) || "jpeg".equalsIgnoreCase(sysFile.getFileType())){
                    try {
                        map.put("imgUrl",Pictures.ofStream(new FileInputStream(sysFile.getFilePath()), PictureType.JPEG)
                                .size(300, 150).create());
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }else if("png".equalsIgnoreCase(sysFile.getFileType())){
                    try {
                        map.put("imgUrl",Pictures.ofStream(new FileInputStream(sysFile.getFilePath()), PictureType.PNG)
                                .size(300, 150).create());
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }else if("gif".equalsIgnoreCase(sysFile.getFileType())){
                    try {
                        map.put("imgUrl",Pictures.ofStream(new FileInputStream(sysFile.getFilePath()), PictureType.GIF)
                                .size(300, 150).create());
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                teacherImgMapList.add(map);
            }
        }

        paramsMap.put("teacherImgMapList",teacherImgMapList);
        paramsMap.put("explain",teacherAnalysisImprovement.getExplain());
        paramsMap.put("measuresJson",teacherAnalysisImprovement.getMeasuresJson());

        List<Map<String,Object>> queMapImgList = new ArrayList<>();
        List<String> queImgList = Arrays.asList(reportBaseinfo.getStudentQuestionnaire().split(";"));
        if(imgList.size() > 0){
            for (String s : queImgList) {
                SysFile sysFile = fileMapper.selectByName(s);
                Map<String,Object> map = new HashMap<>();
                if("jpg".equalsIgnoreCase(sysFile.getFileType()) || "jpeg".equalsIgnoreCase(sysFile.getFileType())){
                    try {
                        map.put("imgUrl",Pictures.ofStream(new FileInputStream(sysFile.getFilePath()), PictureType.JPEG)
                                .size(250, 150).create());
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }else if("png".equalsIgnoreCase(sysFile.getFileType())){
                    try {
                        map.put("imgUrl",Pictures.ofStream(new FileInputStream(sysFile.getFilePath()), PictureType.PNG)
                                .size(250, 150).create());
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }else if("gif".equalsIgnoreCase(sysFile.getFileType())){
                    try {
                        map.put("imgUrl",Pictures.ofStream(new FileInputStream(sysFile.getFilePath()), PictureType.GIF)
                                .size(250, 150).create());
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                queMapImgList.add(map);
            }
        }
        paramsMap.put("queMapImgList",queMapImgList);
        paramsMap.put("causeJson",teacherAnalysisImprovement.getCauseJson());
        paramsMap.put("auditOpinion",reportBaseinfo.getAuditOpinion());
        SimpleDateFormat f = new SimpleDateFormat("yyyy年MM月dd日");
        paramsMap.put("audittime",f.format(reportBaseinfo.getAudittime()));



        HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();
        LoopColumnTableRenderPolicy columnPolicy = new LoopColumnTableRenderPolicy();
        Configure configure = Configure.builder().bind("reportTargetObservationContactList",policy)
                .bind("gradeMapList",policy)
                .bind("scoreMapList",columnPolicy)
                .bind("reportUsualScoreStandardList",policy)
                .build();


        String wordPath = WordUtil.createWord(templatePath, fileDir, fileShowName, paramsMap,configure);

        File file = new File(wordPath);
        MultipartFile multipartFile = FileToMultipartFileUtil.fileToMultipartFile(file);
        try {
            String fileId = SequenceUtil.makeStringId();
            String name = multipartFile.getOriginalFilename();
            String suffixName = name.substring(name.lastIndexOf("."));
            String fileName = fileId + suffixName;
//            String fileDir = LocalDate.now().toString();
//            String parentPath = uploadProperty.getUploadPath() + fileDir;
            String parentPath = uploadProperty.getUploadPath();
            java.io.File filepath = new java.io.File(parentPath, fileName);
            if (!filepath.getParentFile().exists()) {
                filepath.getParentFile().mkdirs();
            }
            SysFile fileDomain = new SysFile();
            multipartFile.transferTo(filepath);
            fileDomain.setId(fileId);
            fileDomain.setFileDesc(name);
            fileDomain.setFileName(fileName);
            fileDomain.setTargetDate(LocalDate.now());
            fileDomain.setFilePath(filepath.getPath());
            fileDomain.setCreateTime(LocalDateTime.now());
            fileDomain.setFileSize(FileUtil.getPrintSize(filepath.length()));
            fileDomain.setFileType(suffixName.replace(".", ""));
            int result = fileMapper.insert(fileDomain);
            return fileId;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 编辑保存信息
     * @param reportBaseinfoModel
     * @return
     */
    @Override
    public boolean update(ReportBaseinfoModel reportBaseinfoModel) {
        SysUser sysUser = (SysUser) SecurityUtil.currentUserObj();
        // 存储基本信息
        ReportBaseinfo reportBaseinfo = reportBaseinfoModel.getReportBaseinfo();
        reportBaseinfo.setUpdateTime(LocalDateTime.now());
        reportBaseinfo.setUpdateBy(sysUser.getUserId());
        reportBaseinfo.setUpdateName(sysUser.getUsername());

        // 存储课程目标
        reportCourseTargetMapper.deleteByReportId(reportBaseinfo.getId().longValue());
        List<ReportCourseTarget> reportCourseTargetList = reportBaseinfoModel.getReportCourseTargetList();
        if(reportCourseTargetList!=null && !reportCourseTargetList.isEmpty()){
            for (ReportCourseTarget reportCourseTarget : reportCourseTargetList) {
                reportCourseTarget.setCreateTime(LocalDateTime.now());
                reportCourseTarget.setCreateBy(sysUser.getUserId());
                reportCourseTarget.setCreateName(sysUser.getUsername());
                reportCourseTarget.setReportId(reportBaseinfo.getId().longValue());
                reportCourseTargetService.insertReportCourseTarget(reportCourseTarget);
            }
        }

        // 存储课程目标与毕业要求观测点的对应关系
        reportTargetObservationContactMapper.deleteByReportId(reportBaseinfo.getId().longValue());
        List<ReportTargetObservationContact> reportTargetObservationContactList = reportBaseinfoModel.getReportTargetObservationContactList();
        if(reportTargetObservationContactList!=null && !reportTargetObservationContactList.isEmpty()){
            for (ReportTargetObservationContact reportTargetObservationContact : reportTargetObservationContactList) {
                reportTargetObservationContact.setCreateTime(LocalDateTime.now());
                reportTargetObservationContact.setCreateBy(sysUser.getUserId());
                reportTargetObservationContact.setCreateName(sysUser.getUsername());
                reportTargetObservationContact.setReportId(reportBaseinfo.getId().longValue());
                reportTargetObservationContactService.insertReportTargetObservationContact(reportTargetObservationContact);
            }
        }

        // 存储评价内容与学生能力相关性
        reportEvaluateAbilityRelevanceMapper.deleteByReportId(reportBaseinfo.getId().longValue());
        List<ReportEvaluateAbilityRelevance> reportEvaluateAbilityRelevanceList = reportBaseinfoModel.getReportEvaluateAbilityRelevanceList();
        if(reportEvaluateAbilityRelevanceList!=null && !reportEvaluateAbilityRelevanceList.isEmpty()){
            for (ReportEvaluateAbilityRelevance reportEvaluateAbilityRelevance : reportEvaluateAbilityRelevanceList) {
                reportEvaluateAbilityRelevance.setCreateTime(LocalDateTime.now());
                reportEvaluateAbilityRelevance.setCreateBy(sysUser.getUserId());
                reportEvaluateAbilityRelevance.setCreateName(sysUser.getUsername());
                reportEvaluateAbilityRelevance.setReportId(reportBaseinfo.getId().longValue());
                reportEvaluateAbilityRelevanceService.insertReportEvaluateAbilityRelevance(reportEvaluateAbilityRelevance);
            }
        }

        // 存储考核合理性审核
        reportAssessmentRationalityMapper.deleteByReportId(reportBaseinfo.getId().longValue());
        ReportAssessmentRationality reportAssessmentRationality = reportBaseinfoModel.getReportAssessmentRationality();
        reportAssessmentRationality.setUpdateTime(LocalDateTime.now());
        reportAssessmentRationality.setUpdateBy(sysUser.getUserId());
        reportAssessmentRationality.setUpdateName(sysUser.getUsername());
        reportAssessmentRationality.setReportId(reportBaseinfo.getId().longValue());
        reportAssessmentRationalityService.insertReportAssessmentRationality(reportAssessmentRationality);

        // 存储平时成绩评分标准
        reportUsualScoreStandardMapper.deleteByReportId(reportBaseinfo.getId().longValue());
        List<ReportUsualScoreStandard> reportUsualScoreStandardList = reportBaseinfoModel.getReportUsualScoreStandardList();
        if(reportUsualScoreStandardList!=null && !reportUsualScoreStandardList.isEmpty()){
            for (ReportUsualScoreStandard reportUsualScoreStandard : reportUsualScoreStandardList) {
                reportUsualScoreStandard.setCreateTime(LocalDateTime.now());
                reportUsualScoreStandard.setCreateBy(sysUser.getUserId());
                reportUsualScoreStandard.setCreateName(sysUser.getUsername());
                reportUsualScoreStandard.setReportId(reportBaseinfo.getId().longValue());
                reportUsualScoreStandardService.insertReportUsualScoreStandard(reportUsualScoreStandard);
            }
        }

        // 存储评价结果
        reportEvaluationResultsMapper.deleteByReportId(reportBaseinfo.getId().longValue());
        List<ReportEvaluationResults> reportEvaluationResultsList = reportBaseinfoModel.getReportEvaluationResultsList();
        if(reportEvaluationResultsList!=null && !reportEvaluationResultsList.isEmpty()){
            for (ReportEvaluationResults reportEvaluationResults : reportEvaluationResultsList) {
                reportEvaluationResults.setCreateTime(LocalDateTime.now());
                reportEvaluationResults.setCreateBy(sysUser.getUserId());
                reportEvaluationResults.setCreateName(sysUser.getUsername());
                reportEvaluationResults.setReportId(reportBaseinfo.getId().longValue());
                reportEvaluationResultsService.insertReportEvaluationResults(reportEvaluationResults);
            }
        }

        // 存储任课教师分析与改进
        teacherAnalysisImprovementMapper.deleteByReportId(reportBaseinfo.getId().longValue());
        TeacherAnalysisImprovement teacherAnalysisImprovement = reportBaseinfoModel.getTeacherAnalysisImprovement();
        teacherAnalysisImprovement.setUpdateTime(LocalDateTime.now());
        teacherAnalysisImprovement.setUpdateBy(sysUser.getUserId());
        teacherAnalysisImprovement.setUpdateName(sysUser.getUsername());
        teacherAnalysisImprovement.setReportId(reportBaseinfo.getId().longValue());
        teacherAnalysisImprovementService.insertTeacherAnalysisImprovement(teacherAnalysisImprovement);

        reportBaseinfo.setWordId(saveWord(reportBaseinfoModel));
        updateReportBaseinfo(reportBaseinfo);

        return true;
    }
}
